package com.xiaomi.shoppinglist

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
class ReminderService : Service() {
    private val TAG = "ReminderService"
    private val CHANNEL_ID = "SHOPPING_LIST_REMINDER"
    private var timer: Timer? = null

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "Service created")

        // 初始化数据库
        ShoppingListDatabase.init(this)

        // 启动定时检查
        startChecking()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "Service started")
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "Service destroyed")
        // 取消定时任务
        timer?.cancel()
    }

    private fun startChecking() {
        // 每小时检查一次
        timer = Timer()
        timer?.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                checkReminders()
            }
        }, 0, 60 * 60 * 1000) // 1小时
    }

    private fun checkReminders() {
        Log.d(TAG, "Checking reminders")
        val db = ShoppingListDatabase.getInstance(this)

        CoroutineScope(Dispatchers.IO).launch {
            val items = db.shoppingItemDao().getRemindableItems()

            for (item in items) {
                if (item.shouldRemind()) {
                    // 重置项的完成状态
                    item.resetCompletion()
                    db.shoppingItemDao().update(item)

                    // 显示通知
                    showNotification(item)
                }
            }

            // 更新小部件
            updateWidgets()
        }
    }

    private fun showNotification(item: ShoppingItem) {
        val intent = Intent(this, AddItemActivity::class.java)
        val pendingIntent = android.app.PendingIntent.getActivity(
            this, 0, intent, android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE
        )

        val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("购物清单提醒")
            .setContentText("是时候购买: ${item.name}")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)

        with(NotificationManagerCompat.from(this)) {
            notify(item.id.toInt(), builder.build())
        }
    }

    private fun updateWidgets() {
        val intent = Intent(android.appwidget.AppWidgetManager.ACTION_APPWIDGET_UPDATE)
        sendBroadcast(intent)
    }
}